<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
            <el-form-item label="楼宇" prop="buildId">
                <el-input v-model="queryParams.buildId" placeholder="请选择楼宇" clearable size="small" style="width: 240px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="时间范围" prop="dateRange">
                <el-date-picker v-model="queryParams.dateRange" type="monthrange" range-separator="到"
                    start-placeholder="开始时间" end-placeholder="结束时间" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd"
                    v-hasRole="['plumber']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" size="mini" @click="handleDelete2"
                    v-hasRole="['plumber2']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" size="mini" @click="handleExport"
                    v-hasRole="['plumber2']">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格数据 -->
        <el-table v-loading="loading" :data="recordList" stripe border>
            <el-table-column label="宿舍" prop="dormName" :show-overflow-tooltip="true" width="100" sortable />
            <el-table-column label="描述" prop="context" :show-overflow-tooltip="true" width="240" sortable />
            <el-table-column label="图片" prop="picture" width="90" sortable>
                <template #default="scope">
                    <el-button size="mini" v-if="scope.row.picture != '' && scope.row.picture != null" type="text"
                        @click="showImages(scope.row)" v-hasRole="['plumber']">点击查看</el-button>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" :show-overflow-tooltip="true" prop="addTime" width="180"
                sortable />
            <el-table-column label="处理反馈" align="center" :show-overflow-tooltip="true" prop="feedback" width="260"
                sortable />
            <el-table-column label="处理人员" align="center" :show-overflow-tooltip="true" prop="handleWorkName" width="140"
                sortable />
            <el-table-column label="处理时间" align="center" :show-overflow-tooltip="true" prop="handleTime" width="180"
                sortable />
            <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="80">
                <template #default="scope">
                    <el-button size="mini" v-if="scope.row.handleWorkName == '' || scope.row.handleWorkName == undefined"
                        type="text" @click="updateShow(scope.row)" v-hasRole="['plumber']">处理</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <el-dialog title="图片展示" v-model="imageDialogOpen" width="600px" append-to-body>
            <el-carousel height="300px">
                <el-carousel-item v-for="item in imgs" :key="item">
                    <el-image style="width: 580px; height: 490px" :src="i" fit="contain" />
                </el-carousel-item>
            </el-carousel>
        </el-dialog>

        <el-dialog title="维修后反馈" v-model="open" width="500px">
            <el-form ref="formRef" :model="updateForm" :rules="rules2" label-width="80px">
                <el-form-item label="处理时间" prop="handleTime">
                    <el-date-picker v-model="updateForm.handleTime" type="datetime" placeholder="请选择处理时间" />
                </el-form-item>
                <el-form-item label="处理反馈" prop="feedback">
                    <el-input v-model="updateForm.feedback" :rows="3" type="textarea" placeholder="请输入处理意见" />
                </el-form-item>
            </el-form>
            <el-form class="btnGroup">
                <el-button size="large" :loading="updateLoading" type="primary" @click="update">确 定</el-button>
                <el-button size="large" @click="cancel">取 消</el-button>
            </el-form>
        </el-dialog>

        <el-dialog title="宿舍财产维修申请" v-model="showAddDiglog">
            <el-form ref="formRef2" :model="addForm" :rules="rules2" label-width="60px">
                <el-form-item label="宿舍" prop="dormId">
                    <el-select v-model="addForm.buildId" placeholder="请选择楼宇" @change="changeBuild">
                        <el-option v-for="item in buildings" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="addForm.dormId" placeholder="请选择宿舍" @change="changeDorm">
                        <el-option v-for="item in dorms" :key="item.id" :label="item.dormName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="内容" prop="context">
                    <el-input v-model="addForm.context" type="textarea" :rows="4" placeholder="请描述损坏物品详情" />
                </el-form-item>
                <el-form-item label="图片" prop="images">
                    <el-upload v-model:file-list="fileList" :action="uploadUrl" :multiple="true" :limit="9"
                        :before-upload="beforeUpload" :on-success="onSuccess" :on-preview="onPreview" :on-remove="onRemove"
                        list-type="picture-card">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    最多只能上传9张图片
                </el-form-item>
            </el-form>
            <el-form class="btnGroup">
                <el-button size="large" :loading="addLoading" type="primary" @click="addFormSubmit">确 定</el-button>
                <el-button size="large" @click="cancel2">取 消</el-button>
            </el-form>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="图片预览" />
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script setup name="plumberPropertyInfo">
import { ElNotification } from 'element-plus'
import { recordListApi, updateRepairApi, getBuildingApi, getDormApi, adddormPropertyMainTainApi } from '@/api/plumber'

const { proxy } = getCurrentInstance();

const recordList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const imageDialogOpen = ref(false)
const imgs = ref([])
const open = ref(false)
const updateForm = ref('')
const updateLoading = ref(false)
const showAddDiglog = ref(false)
const addLoading = ref(false)


const buildings = ref([])
const dorms = ref([])

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        buildId: undefined,
        dateRange: undefined
    }
});

const { queryParams, form } = toRefs(data);

const data2 = reactive({
    addForm: {
        dormId: '',
        context: '',
        pictures: []
    },
    rules2: {
        dormId: [{ required: true, message: "宿舍不能没有选择", trigger: "blur" }],
        context: [{ required: true, message: "损坏物品描述不能为空", trigger: "blur" }]
    },
});

const { addForm, rules2 } = toRefs(data2);

const fileList = ref([])

const uploadUrl = reactive('http://localhost:10011/file/upload')

const changeBuild = (val) => {
    addForm.value.buildId = val
    addForm.value.dormId = ''
    dorms.value = []
    getDorms(val)
}

const changeDorm = (val) => {
    addForm.value.dormId = val
}

const getBuildings = () => {
    getBuildingApi().then(res => {
        if (res.code == 200) {
            buildings.value = res.data
        }
    })
}
getBuildings()

const getDorms = (val) => {
    getDormApi(val).then(res => {
        if (res.code == 200) {
            dorms.value = res.data
        }
    })
}

/** 查询我的填写访客列表 */
const getList = () => {
    loading.value = true;
    recordListApi(queryParams.value).then(res => {
        if (res.code == 200) {
            recordList.value = res.data.vo;
            total.value = res.data.total;
            loading.value = false;
        } else {
            recordList.value = [];
            total.value = 0;
            loading.value = false;
        }
    })
}
getList();
/**
 * 点击展开图片
 * @param {*} row 
 */
const showImages = (row) => {
    imgs.value = row.picture.split(",")
    imageDialogOpen.value = true
}
/**
 * 更新维修信息
 */
const update = () => {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            addLoading.value = true
            console.log(addForm.value);
            updateRepairApi(updateForm.value).then(res => {
                if (res.code == 200) {
                    ElNotification({
                        title: '提示',
                        message: '修改成功',
                        type: 'success'
                    })
                    addLoading.value = false;
                    getList()
                    cancel()
                }
            }).catch(err => {
                addLoading.value = false;
            })
        }
    });
}
/**
 * 更新维修信息取消
 */
const cancel = () => {
    updateLoading.value = false
    open.value = false
    proxy.resetForm("formRef")
    updateForm.value = ''
}
/**
 * 添加维修信息取消
 */
const cancel2 = () => {
    addLoading.value = false
    showAddDiglog.value = false
    proxy.resetForm("formRef2")
    addForm.value = ''
}
/** 提交新增维修表单 */
const addFormSubmit = () => {
    proxy.$refs["formRef2"].validate(valid => {
        if (valid) {
            addLoading.value = true
            console.log(addForm.value);
            adddormPropertyMainTainApi(addForm.value).then(res => {
                if (res.code == 200) {
                    ElNotification({
                        title: '提示',
                        message: '添加成功',
                        type: 'success'
                    })
                    addLoading.value = false
                    proxy.resetForm("formRef2")
                    addForm.value.pictures = []
                    fileList.value = []
                    showAddDiglog.value = false
                    getList()
                }
            }).catch(err => {
                addLoading.value = false
            })
        }
    });
}
const handleAdd = () => {
    showAddDiglog.value = true
}

const updateShow = (row) => {
    updateForm.value = row
    open.value = true
}
const beforeUpload = (file) => {
    const isJPG = file.type === "image/jpeg";
    const isPNG = file.type === "image/png";
    const isGIF = file.type === "image/gif";

    if (!isJPG && !isPNG && !isGIF) {
        proxy.$modal.msgError("请选择JPG/PNG/GIF格式的图片");
        return false;
    }

    // check image size
    const isLt10M = file.size / 1024 / 1024 < 2;
    if (!isLt10M) {
        proxy.$modal.msgError("图片必须小于2MB!");
        return false;
    }
    return true;
}

const onSuccess = (res, file, fileList) => {
    if (res.code == 200) {
        addForm.value.pictures.push(res.data)
    }
}

const onPreview = (file) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}

const onRemove = (uploadFile, uploadFiles) => {
    proxy.$modal.msgError("您移除了图片" + uploadFile.name)
    addForm.value.pictures = addForm.value.pictures.filter(item => item != uploadFile.response.data)
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}
/** 导出按钮操作 */
function handleExport() {
    // proxy.download("system/role/export", {
    //     ...queryParams.value,
    // }, `role_${new Date().getTime()}.xlsx`);
}
/** 多选框选中数据 */
// function handleSelectionChange(selection) {
//     ids.value = selection.map(item => item.id)
// }
</script>